#coding=utf-8
from web.handler.api import BaseApiHandler
from lib.tornado_routes import route
import os
import upload
import string
from PIL import Image
import libimg

head_title = '图片操作'

@route(r'api/image/upload/get/?',name='image_get')
class getpath(BaseApiHandler):
	'''
	@title 获取用户所有图片
	@method post
	@param username 用户名 默认:''
	@param passwd 密码 默认：''
	@param path 路径 默认：'根目录'
	@retfield isOk 发布成功与否1成功0失败 
	@retfield date ['...', '...', ...]path 
	@return {status:200, message:'', data:null}---status:500(系统错误)400(请传入必要参数)
	@description 获取用户所有图片
	'''
	def get(self):
		self.write('''<html><body>
<form method="POST" action="/api/image/upload/get/" enctype="multipart/form-data">
File #1: <input name="username" type="text"><br>
File #2: <input name="passwd" type="text"><br>
File #3: <input name="path" type="text"><br>
<input type="submit">
</form>
</body></html>''')

	def post(self):
		ret = ""

		username = self.request.arguments.get('username')[0]
		passwd = self.request.arguments.get('passwd')[0]
		path = self.request.arguments.get('path')[0]

		if username not in upload.listuser or passwd not in upload.listpasswd:
			self.write_fail(None, 400, '用户名密码错误')
			return
		if path is None or path == '':
			path = '.'
		elif '.' in path:
			self.write_fail(None, 500, '输入的路径不正确')
			return
		imgpath = ''.join([upload.upload_path, '/', username, '/', path])
		if os.path.exists(imgpath):
			ret = listdir(imgpath)

		self.write_success({'isOk':1, 'paths':str(ret)})


@route(r'api/image/upload/del/?',name='image_del')
class imgdel(BaseApiHandler):
	'''
	@title 删除指定图片
	@method post
	@param username 用户名 默认:''
	@param passwd 密码 默认：''
	@param path 路径 默认：''
	@param imgname 路径 默认：''
	@retfield isOk 发布成功与否1成功0失败 
	@return {status:200, message:'', data:null}---status:500(系统错误)400(请传入必要参数)
	@description 删除指定图片
	'''
	def get(self):
		self.write('''<html><body>
<form method="POST" action="/api/image/upload/del/" enctype="multipart/form-data">
File #1: <input name="username" type="text"><br>
File #2: <input name="passwd" type="text"><br>
File #3: <input name="path" type="text"><br>
File #3: <input name="imgname" type="text"><br>
<input type="submit">
</form>
</body></html>''')

	def post(self):
		ret = ""

		username = self.request.arguments.get('username')[0]
		passwd = self.request.arguments.get('passwd')[0]
		path = self.request.arguments.get('path')[0]
		imgname = self.request.arguments.get('imgname')[0]

		if username not in upload.listuser or passwd not in upload.listpasswd:
			self.write_fail(None, 400, '用户名密码错误')
			return
		if path is None or path == '' or '.' in path:
			self.write_fail(None, 500, '输入的路径不正确')
			return
		if imgname is None or imgname == '' or len(imgname.split('.'))>2:
			self.write_fail(None, 500, '输入的文件名不正确')
			return
		imgpath = ''.join([upload.upload_path, '/', username, '/', path, '/', imgname])
		if os.path.exists(imgpath):
			if os.path.isfile(imgpath):
				os.remove(imgpath)
				if not os.listdir(''.join([upload.upload_path, '/', username, '/', path])):
					os.rmdir(''.join([upload.upload_path, '/', username, '/', path]))
			else:
				self.write_fail(None, 400, '文件不存在')
		else:
			self.write_fail(None, 400, '文件不存在')

		self.write_success({'isOk':1})

@route(r'api/(?P<username>.*)/uploads/(?P<path>.*)/(?P<filename>.*)',name='image_cat')
class imgcat(BaseApiHandler):
	'''
	@title 获取图片
	@method post
	@param username 用户名 默认:''
	@param path 路径 默认：''
	@param w 宽度 选填：宽度限定高度不限
	@param h 高度 选填：宽度不限高度限定
	@retfield isOk 发布成功与否1成功0失败 
	@return {status:200, message:'', data:null}---status:500(系统错误)400(请传入必要参数)
	@description 获取图片
	'''
	def get(self, username, path, filename):
		if '.' in username or '.' in path or len(filename.split('.'))>2:
			self.write('400 NOT FIND')
			return
		if path == 'root':
			path = ''
		imagepath = os.path.join(upload.upload_path, username, path)
		if not os.path.exists(imagepath):
			self.write('404 NOT FIND')
			return

		try:
			w = self.get_argument('w', default='0')
			h = self.get_argument('h', default='0')
			if w == '0' and h == '0':
				self.set_header("Content-Type", "application/octet-stream")
				with open(os.path.join(imagepath, filename), 'rb') as img:
					self.write(img.read())
					img.close()
			else:
				w = string.atoi(w)
				h = string.atoi(h)
				if w == 0 and h != 0:
					w = h*100
				elif w != 0 and h ==0:
					h = w*100
				if not os.path.exists(os.path.join(imagepath, str(w) + '#' + str(h), filename)):
					if not os.path.exists(os.path.join(imagepath, str(w) + '#' + str(h))):
						os.mkdir(os.path.join(imagepath, str(w) + '#' + str(h)))
					libimg.thumbnail(w, h, os.path.join(imagepath, filename)
						, os.path.join(imagepath, str(w) + '#' + str(h), filename))

				self.set_header("Content-Type", "application/octet-stream")
				with open(os.path.join(imagepath, str(w) + '#' + str(h), filename), 'rb') as img:
					self.write(img.read())
					img.close()

		except Exception, e:
			self.write('参数传入错误')
			print e

def listdir(dir1):
    a=[]
    s=os.walk(dir1)
    #num=len(s)
    stmp=0
    sum=1
    for x in s:
        stmp+=1
        for i in range(len(x[2])):
        	sp = (str(x[0])+'/'+str(x[2][i])).split(dir1)[1]
        	a.append(sp)
    return a